package gr.unipi.soap;

import gr.unipi.cinema.ReserveData;
import gr.unipi.cinema.SqlConnection;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class Reservation {
	
	public static int makeReservation(String cusName, String cusAddr, String cusPhone, 
			String cusCard, String cusCsv, String expDate, ReserveData[] data, int showId, double totCost) {
		
		int res = -1;
		Connection connection = SqlConnection.getConnection();
		if ((connection == null) || (data == null)) {
			System.out.println("Error");
			return res;
		}
		
		
		PreparedStatement st = null;
		ResultSet resultSet = null;
		
		try {
			connection.setAutoCommit(false);
			st = connection.prepareStatement(
					"INSERT INTO CRESERVATIONS " +
					"(CUSNAME, CUSADDR, CUSPHONE, CREDITCARDNUM, CREDITCARDEXP, CREDITCARDCSV, SHOWID, TOTCOST) " +
					"VALUES (?, ?, ?, ?, ?, ?, ?, ?) ",
					Statement.RETURN_GENERATED_KEYS);
			
			st.setString(1, cusName);
			st.setString(2, cusAddr);
			st.setString(3, cusPhone);
			st.setString(4, cusCard);
			
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd", Locale.FRANCE);
			
			Date d = dateFormat.parse(expDate);
			st.setTimestamp(5, new Timestamp(d.getTime()));
			
			st.setString(6, cusCsv);
			st.setInt(7, showId);
			st.setDouble(8, totCost);
			
			st.executeUpdate();
			
			resultSet = st.getGeneratedKeys();
			if (resultSet.next()) {
				res = resultSet.getInt(1);
			}
			else {
				return res;
			}
			
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			st = null;
			
			st = connection.prepareStatement(
					"INSERT INTO CRESERVSEATS " +
					"(RESERVID, ROWID, COLID) " +
					"VALUES (" + res + ", ?, ?) ");
			
			for (int i = 0; i < data.length; i++) {
				st.setInt(1, data[i].getRowId());
				st.setInt(2, data[i].getColId());
				st.executeUpdate();
			}
			connection.commit();
			
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		finally {
			
			if (resultSet != null) {
				try {
					resultSet.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
				resultSet = null;
			}
			
			if (st != null) {
				try {
					st.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
				st = null;
			}
			
			try {
				connection.rollback();
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			connection = null;
		}
		
		return res;
	}
}
